package api.net;

import api.interfaceapi.APIMsgParams;
import api.utils.MyHttpLoggingInterceptor;
import api.utils.ToolsAPI;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import okhttp3.*;
import okio.Buffer;
import retrofit2.Retrofit;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class RequestBase {
    private static RequestBase requestBase = null;
    public static String Authorization = "";

    private RequestBase() {

    }

    public static RequestBase getInstank() {
        if (requestBase == null) {
            requestBase = new RequestBase();
        }
        return requestBase;
    }

    boolean test = false;

    public RequestURLAPP getRetrofit(APIMsgParams apiMsgParams) {

        Gson gson = new GsonBuilder()
                .setLenient()
                .create();
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
//        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
//        logging.setLevel(HttpLoggingInterceptor.Level.BODY);
//        builder.addInterceptor(logging);
        builder.addInterceptor(new MyHttpLoggingInterceptor(apiMsgParams));
        builder.connectTimeout(5, TimeUnit.SECONDS);
        builder.readTimeout(5, TimeUnit.SECONDS);
        builder.writeTimeout(5, TimeUnit.SECONDS);
        builder.addInterceptor(chain -> {
            Request request = chain.request()
                    .newBuilder()
                    .addHeader("Authorization", Authorization)
                    .addHeader("Content-Type", "application/json;charset=UTF-8")
                    .addHeader("content-type", "application/json;charset=UTF-8")
                    .addHeader("accept", "application/json")
                    .build();
            if (test) {
                //用于模拟后台返回数据，测试用例是否正确
                File errefilePath = new File(ToolsAPI.class.getClassLoader().getResource("TestAPIjson.txt").getFile());
                String responseJson = FileInputStream(errefilePath).replaceAll("\u0000", "").replace("\n", "");
                Request.Builder request_2 = request.newBuilder();
                request = request_2.addHeader("Content-Type", "application/json;charset=UTF-8")
                        .post(RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), bodyToString(request.body())))
                        .build();
                Response response = chain.proceed(request);
                ResponseBody myBody = ResponseBody.create(MediaType.get("text/plain"), responseJson);
                return response.newBuilder().body(myBody).build();
            }
            return chain.proceed(request);
        });
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(RequestURLAPP.HOST)
                .addConverterFactory(CustomGsonConverterFactory.create(gson))
                .client(builder.build())
                .build();

        return retrofit.create(RequestURLAPP.class);
    }


    //读取文件内容
    public String FileInputStream(File file) throws IOException {
        if (!file.exists() || file.isDirectory())
            throw new FileNotFoundException();
        FileInputStream fis = new FileInputStream(file);
        byte[] buf = new byte[1024];
        StringBuffer sb = new StringBuffer();
        while ((fis.read(buf)) != -1) {
            sb.append(new String(buf));
            buf = new byte[1024];//重新生成，避免和上次读取的数据重复
        }
        fis.close();
        return sb.toString();
    }

    private static String bodyToString(final RequestBody request) {
        try {
            final RequestBody copy = request;
            final Buffer buffer = new Buffer();
            if (copy != null)
                copy.writeTo(buffer);
            else
                return "";
            return buffer.readUtf8();
        } catch (final IOException e) {
            return "did not work";
        }
    }
}
